package com.zh.template;

import com.zh.exception.GlobalException;
import com.zh.properties.IDCardProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * 微信相关的工具类  身份实名认证二要素
 */
@Slf4j
public class IDCardTemplate {


    private  IDCardProperties idCardProperties;

    public IDCardTemplate(IDCardProperties idCardProperties) {
        this.idCardProperties = idCardProperties;
    }

    /**
     * 身份证二要素识别认证
     * @param name
     * @param idNo
     * @return
     * @throws IOException
     */
    public  String postData( String name, String idNo) throws IOException {
        String result = "";
        RequestBody formBody = new FormBody.Builder().add("name", name).add("idNo", idNo).build();
        Request request = new Request.Builder().url(idCardProperties.getUrl()).addHeader("Authorization", "APPCODE " + idCardProperties.getAppCode()).post(formBody).build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (Exception e) {
            log.error("execute failed, message:{}" ,e.getMessage());
            throw new GlobalException("Unexpected code " + e);
        }
        assert response != null;
        if (!response.isSuccessful()) {      // 当返回结果发生错误时
            // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            log.error("request failed----返回状态码 {}, message: {}" , response.code() ,response.message());
        }
        result = response.body().string();    //此处不可以使用toString()方法，该方法已过期

        return result;
    }
}
